// Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php 

library gen_hdmi_no_screen_poweroff;

uses
  SysUtils,  Windows,  Messages,  ExtCtrls;

{$R *.RES}



type
  TDisplayHandler = class
  public
    procedure TimerTimer(Sender: TObject);
  end;


var
  Timer: TTimer;
  Handler: TDisplayHandler;


type
  TwinampGeneralPurposePlugin = record
    version: integer;
    description: PAnsiChar;
    InitPinteger: function: integer; cdecl;
    Pconfig: procedure; cdecl;
    Pquit: procedure; cdecl;

    hwndParent: integer;
    hDllInstance: LongWord;
  end;

type
  PTwinampGeneralPurposePlugin = ^TwinampGeneralPurposePlugin;

var
  plugin: TwinampGeneralPurposePlugin;

const
  icversion: integer  = $10; //If you change it it woun't work but I don't know why :-(  !
  ichwndParent: integer  = 0;
  lwchDllInstance: LongWord = 0;
  pccdescription: PAnsiChar = 'HDMI screen poweroff preventer' + #0;

function IsPlaying: boolean;
begin
  Result := SendMessage(plugin.hwndParent, WM_USER, 0, 104) = 1;
end;

function Init: integer;  cdecl;    //Do some inits here and return with result of them .
begin
  Timer := TTimer.Create(nil);
  Handler := TDisplayHandler.Create;

  Timer.OnTimer := Handler.TimerTimer;

  Result := 0;
end;

procedure config; cdecl;
begin
 ;
end;

procedure quit; cdecl;
begin
  FreeAndNil(Timer);
  FreeAndNil(Handler);
end;

function winampGetGeneralPurposePlugin(): Pointer; cdecl; //Don't change function name and its result type.
begin
  plugin.version      := icversion;
  plugin.description  := pccdescription;
  plugin.InitPinteger := @Init;
  plugin.Pconfig      := @config;
  plugin.Pquit        := @quit;

  Result := @plugin;
end;


{ TDisplayHandler }

type
  EXECUTION_STATE = DWORD;

const
  ES_SYSTEM_REQUIRED = $00000001;
  ES_DISPLAY_REQUIRED = $00000002;
  ES_USER_PRESENT = $00000004;
  ES_AWAYMODE_REQUIRED = $00000040;
  ES_CONTINUOUS = $80000000;

  KernelDLL = 'kernel32.dll';


procedure SetThreadExecutionState(ESFlags: EXECUTION_STATE) ; stdcall; external kernel32 name 'SetThreadExecutionState';

procedure TDisplayHandler.TimerTimer(Sender: TObject);
begin
  if IsPlaying then
    SetThreadExecutionState(ES_SYSTEM_REQUIRED or ES_DISPLAY_REQUIRED or ES_CONTINUOUS)
  else
    SetThreadExecutionState(ES_CONTINUOUS)
end;

exports winampGetGeneralPurposePlugin;

begin

end.
